/****************************************************************************
 * recover.c
 *
 * Arcadie Condrat
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 ***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// JPEG SOI: 0xff 0xd8 0xff 0xe0 or 0xff 0xd8 0xff 0xe1
// JPEG EOI: 0xff 0xd9
typedef uint8_t  BYTE;

int main(int argc, char* argv[])
{
    // ensure proper usage
    if (argc != 1)
    {
        printf("No parameters allowed!\n");
		return 1;
	}
		
	// open input file 
    FILE* inptr = fopen("card.raw", "r");
    if (inptr == NULL)
    {
        printf("Could not open image file\n");
        return 2;
    }
    
	int EOI = 0;
	int file_index = 0;
    BYTE block[512];
    char buffer [8];
	while (1)
    {
		if (fread(&block, sizeof(BYTE), 512, inptr) == 0 )
		{
			fclose(inptr);
			return 0;
		}
		else
		{
			if ((block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff) && (block[3] == 0xe0 || block[3] == 0xe1))
			{ 
				EOI = 0;
				sprintf(buffer, "%0.3d.jpg", file_index);
				FILE* outptr = fopen(buffer, "w");
				if (outptr == NULL)
				{
					fclose(inptr);
					fprintf(stderr, "Could not create output file\n");
					return 3;
				}
				while (EOI == 0)
				{	
					fwrite(&block, sizeof(BYTE), 512, outptr);
					if (fread(&block, sizeof(BYTE), 512, inptr) == 0 )
					{
						fclose(inptr);
						fclose(outptr);
						return 0;
					}
					// check if SOI is present in this block
					if ((block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff) && (block[3] == 0xe0 || block[3] == 0xe1))
					{	
						EOI = 1;
						fclose(outptr);
						file_index++;
						fseek(inptr, -(sizeof(BYTE) * 512), SEEK_CUR);
					}
				}			
			}		
		}
	}
	
	// close infile
    fclose(inptr);

    return 0;
}

